package plgnet

import (
	"dgo/MyProj/PrjHttpUtils"
	"dgo/goutils/gohttp"
	"dgo/goutils/utils"
	"fmt"
	"gitee.com/ymofen/supervalue"
	"net/http"
)

type PlgHttpBase struct {
	PlgBase
	// 注册的uri
	api_uri_map utils.GSyncMapGroup

	api_prefix string

	// 是否运行跨域
	Http_allow_cross_access bool

	OnReleaseFunc       func()
	OnRegisterApiFunc   func(api_prefix string)
	OnUnRegisterApiFunc func(api_prefix string)
	OnReloadConfFunc    func(conf *wrapper.SuperValue)
}

func NewPlgHttpBase() *PlgHttpBase {
	rval := &PlgHttpBase{}
	return rval
}

func (this *PlgHttpBase) UnRegisterAPI(key string) {
	uri := this.api_uri_map.Get(key, "").(string)
	if len(uri) > 0 {
		gohttp.UnHandle(uri)
	}
	this.api_uri_map.Remove(key)
}

func (this *PlgHttpBase) CheckRegisterApi(key string, uri string, fn http.HandlerFunc) {
	uri0 := this.api_uri_map.Get(key, "").(string)
	if uri0 != uri {
		if len(uri0) > 0 {
			gohttp.UnHandle(uri)
		}
		this.api_uri_map.Set(key, uri)
		if len(uri) > 0 {
			gohttp.HandleFunc(uri, fn)
		}
	}
}

/*
*

	  {
		  "id": "http-helper",
		  "type": "http.base",
		  "conf": {
			"http-allow-cross-access": true,  // 允许跨域访问
	        "api-prefix":"/api/web/"
	      }
	  }
*/
func (this *PlgHttpBase) ReloadConf(conf *wrapper.SuperValue) (err error) {
	conf.CheckExistsStrFunc("http-allow-cross-access", func(strv string) {
		this.Http_allow_cross_access = utils.TryStrToBool(strv, false)
	})

	conf.CheckExistsStrFunc("api-prefix", func(strv string) {
		if this.api_prefix != strv {
			if len(this.api_prefix) > 0 {
				if this.OnUnRegisterApiFunc != nil {
					this.OnUnRegisterApiFunc(this.api_prefix)
				}
			}
			this.api_prefix = strv
			if len(this.api_prefix) > 0 {
				if this.OnRegisterApiFunc != nil {
					this.OnRegisterApiFunc(this.api_prefix)
				}
			}
		}
	})

	if this.OnReloadConfFunc != nil {
		this.OnReloadConfFunc(conf)
	}
	return
}

func (this *PlgHttpBase) innerRelease() {
	if len(this.api_prefix) > 0 {
		if this.OnUnRegisterApiFunc != nil {
			this.OnUnRegisterApiFunc(this.api_prefix)
		}
	}

	this.api_uri_map.Range(func(key, value interface{}) bool {
		gohttp.UnHandle(value.(string))
		return true
	})
}

func (this *PlgHttpBase) OnHttpStatus(rec *PlgHttpRec) (rval interface{}, errcode int, err error) {
	itype := rec.QryAsInt("type", 0)
	if itype == 99 {
		json := wrapper.NewSVObject()
		json.SetKeyValues("allow-cross", this.Http_allow_cross_access,
			"api-prefix", this.api_prefix,
		)
		PrjHttpUtils.JSON2TableRec(rec.RespW, "", json.AsJSONString(false))
	} else {
		var sb utils.BytesBuilder
		PrjHttpUtils.AppendIndexBody(&sb, "status", "status?type=99")
		PrjHttpUtils.ResponseBodyHtml(rec.RespW, sb.String())
	}
	return
}

func (this *PlgHttpBase) OnObjectNotify(sender interface{}, notifytype int, data interface{}) (rval interface{}, err error) {
	if notifytype == utils.NOTIFY_TYPE_SETCONF {
		if conf, ok := data.(*wrapper.SuperValue); ok {
			err = this.ReloadConf(conf)
		} else {
			err = fmt.Errorf("非法的JSON配置")
		}
	} else if notifytype == utils.NOTIFY_TYPE_RELEASE {
		if this.OnReleaseFunc != nil {
			this.OnReleaseFunc()
		}
		this.innerRelease()
	}
	return
}

func CreatePlgHttpBaseFunc(args ...interface{}) (rval interface{}, err error) {
	obj := NewPlgHttpBase()
	if len(args) > 0 {
		if str, ok := args[0].(string); ok {
			obj.PlugId = str
		}
	}
	rval = obj
	return
}
